<template lang="pug">
  el-drawer.commonDrawer(
    :title="`${!id ? '添加' : '查看'}班级`"
    :visible="visibleDialog"
    append-to-body
    direction="rtl"
    size="1140px"
    destroy-on-close
    @close="$_handleCancel"
  )
    .drawer-content
      form-box(
        ref="form"
        cancel-text="返回"
        :fields="addConfig"
        :info.sync="info"
        v-loading="loading"
        :disabled="disabled"
        btnClass="tc"
        :showBtns="false"
      )
        template(slot="form-monthRange")
          el-select(v-model="info.beginMonth" style="width: 104px")
            el-option(
              v-for="index in 48"
              :disabled="index > info.endMonth"
              :key="index"
              :value="index"
              :label="`${index}月`"
            )
          small(class="ml5 mr5") 至
          el-select(v-model="info.endMonth" style="width: 104px")
            el-option(
              v-for="index in 48"
              :disabled="index < info.beginMonth"
              :key="index"
              :value="index"
              :label="`${index}月`"
            )
        template(slot="form-teachingAreaIds")
          el-select.w(
            v-model="info.teachingAreaIds"
            multiple
          )
            el-option(
              v-for="item in teachAreas"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            )
          el-link.f13(type="primary" :underline="false" @click="teachAreaVisible = true") 添加教学区域
        el-transfer(
          v-for="(item, key) in transferIds"
          :slot="`form-${key}`"
          :key="key"
          :titles="['未选', '已选']"
          :disabled="key === 'inChargeTeacherId' && item.length === 1"
          filterable
          v-model="transferIds[key]"
          :props="{key: 'id', label: key === 'childrenIds' ? 'name' : 'realName'}"
          :data="transferDataList[key]"
        )
          span(slot-scope="{ option }")
            el-avatar.mr5.vm(:src="option.headImgUrl" :size="24" icon="el-icon-user-solid")
            | {{option[key === 'childrenIds' ? 'name' : 'realName']}}
    .drawer-footer.tr(v-if="!disabled")
      el-button(size="large" round :loading="submitting" @click="$_handleCancel") 取消
      el-button.gradientVertical(size="large" round :loading="submitting" @click="submitHandle") 确定
    teach-area-modal(:visible.sync="teachAreaVisible" @sureHandle="() => getTeachAreaList()" :hidden="true")
</template>
<script>
import { mapGetters } from 'vuex'
import omit from 'lodash/omit'
import uniqBy from 'lodash/uniqBy'
import dictMixin from '@/mixins/dict'
import { getTeachAreas, getTeachersByArea, getDoctorsByArea, getNoClassesByArea, getNurseryClassTypes } from '@/api/common'
import TeachAreaModal from '@/components/Business/TeachAreaModal'
// import { addConfig } from './config'
import { getInfo, submitClass } from './api'

export default {
  components: {
    TeachAreaModal
  },
  mixins: [dictMixin],
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    },
    id: {
      type: [String, Number],
      default: ''
    }
  },
  data () {
    return {
      info: {
        teachingAreaIds: [],
        beginMonth: 0,
        endMonth: 48
      },
      transferIds: {
        inChargeTeacherId: [],
        teacherIds: [],
        doctorIds: [],
        childrenIds: []
      },
      transferData: {
        inChargeTeacherId: [],
        teacherIds: [],
        doctorIds: [],
        childrenIds: []
      },
      submitting: false,
      loading: false,
      teachAreas: [],
      teachAreaVisible: false,

      channel: process.env.VUE_APP_CHANNEL
    }
  },
  computed: {
    ...mapGetters(['curArea']),
    visibleDialog: {
      get () {
        return this.visible
      },
      set (val) {
        this.$emit('update:visible', val)
      }
    },
    transferDataList () {
      const { teacherIds } = this.transferData
      return {
        ...this.transferData,
        // inChargeTeacherId: inChargeTeacherId.map(x => {
        //   x.disabled = this.transferIds.inChargeTeacherId.length > 0
        //   return x
        // }),
        teacherIds: teacherIds.filter(x => !this.transferIds.inChargeTeacherId.includes(x.id))
      }
    },
    addConfig () {
      let teacherLabel = '教保师'
      if (this.channel === 'zidanedu') {
        teacherLabel = '教师'
      }
      const { info: baseData, transferData } = this
      return [
        {
          key: 'name',
          label: '班级名称',
          layoutCol: { sm: 24, md: 14, lg: 12 },
          rules: [{ required: true, message: '请输入' }],
          initialValue: baseData?.name
          // fieldProps: {
          //   style: { width: '240px' }
          // }
        },
        {
          key: 'category',
          layoutCol: { sm: 24, md: 24, lg: 24 },
          type: 'radio',
          label: '班级类型',
          rules: [{ required: true, message: '请选择' }],
          initialValue: String(baseData?.category) || '1',
          fieldProps: {
            changeHandle: val => this.formChange('category', val),
            dictKey: 'classCategory',
            props: { value: 'value', label: 'label' }
          }
        },
        {
          key: 'targetObjectId',
          layoutCol: { sm: 24, md: 14, lg: 12 },
          type: 'select',
          label: '托班类型',
          hidden: String(baseData.category) !== '1',
          rules: [{ required: true, message: '请选择' }],
          initialValue: baseData?.targetObjectId,
          fieldProps: {
            dictKey: 'nurseryClassTypes',
            props: { label: 'label' },
            dictParams: {
              fn: getNurseryClassTypes,
              cb: val => {
                return (val || []).map(x => {
                  x.label = `${x.name}(${x.description})`
                  return x
                })
              }
            }
          }
        },
        {
          key: 'monthRange',
          type: 'slot',
          layoutCol: { sm: 24, md: 24, lg: 24 },
          label: '适用月龄',
          rules: [{ required: true, message: '请输入' }],
          initialValue: `${baseData?.beginMonth} ~ ${baseData?.endMonth}`
        },
        {
          key: 'limitNum',
          type: 'number',
          layoutCol: { sm: 24, md: 24, lg: 24 },
          label: '满额人数',
          rules: [{ required: true, message: '请输入' }],
          initialValue: baseData?.limitNum
        },
        {
          key: 'teachingAreaIds',
          type: 'slot',
          layoutCol: { sm: 24, md: 24, lg: 24 },
          label: '教学区域',
          rules: [{ required: true, message: '请输入' }],
          initialValue: baseData?.teachingAreaIds
        },
        {
          key: 'remark',
          type: 'textarea',
          layoutCol: { sm: 24, md: 24, lg: 24 },
          label: '备注',
          initialValue: baseData?.remark
        },
        {
          key: 'inChargeTeacherId',
          type: 'select',
          layoutCol: { sm: 24, md: 24, lg: 24 },
          label: '班主任',
          rules: [{ required: true, message: '请输入' }],
          fieldProps: {
            options: transferData?.inChargeTeacherId,
            props: { value: 'id', label: 'realName' }
          },
          initialValue: baseData?.inChargeTeacherId
        },
        {
          key: 'teacherIds',
          type: 'slot',
          layoutCol: { sm: 24, md: 24, lg: 24 },
          label: teacherLabel
        },
        {
          key: 'doctorIds',
          type: 'slot',
          layoutCol: { sm: 24, md: 24, lg: 24 },
          label: '儿保医生'
        },
        {
          key: 'childrenIds',
          type: 'slot',
          layoutCol: { sm: 24, md: 24, lg: 24 },
          label: '宝宝'
        }
      ]
    }
  },
  watch: {
    visible: {
      handler (val) {
        if (val) {
          this.getInfo(this.id)
        }
      }
    }
  },
  created () {
  },
  methods: {
    formChange (key, val) {
      this.info = {
        ...this.info,
        [key]: val
      }
    },
    // 获取详情
    getInfo (classesId) {
      if (classesId) {
        this.loading = true
        getInfo({ classesId }).then(res => {
          console.log(res)
          this.info = {
            ...res?.classes,
            teachingAreaIds: (res?.teachingAreaList || []).map(x => x.id),
            ...omit(res, ['classes'])
          }
        }).finally(() => {
          this.getData()
        })
      } else {
        this.info = {}
        this.getData()
      }
    },

    getTeachAreaList () {
      getTeachAreas({ publicFilter: false }, { pageNum: 0, pageSize: 999 }).then(res => {
        this.teachAreas = res?.content || []
      })
    },

    // 获取数据
    async getData () {
      const { info, transferIds, transferData } = this
      const { childrenList = [], teacherList = [], doctorList = [], inChargeTeacherId } = info
      const areaId = this.curArea.areaId
      this.loading = true
      // 获取教学区域
      this.getTeachAreaList()
      // 老师
      const teacherData = await getTeachersByArea({ areaId, pageNum: 0, pageSize: 999 })
      const teachers = teacherData.content

      const doctors = await getDoctorsByArea({ areaId })
      const children = await getNoClassesByArea({ areaId, category: info.category })
      this.loading = false
      transferIds.inChargeTeacherId = inChargeTeacherId?.split(',') || []
      transferData.inChargeTeacherId = uniqBy([
        ...(teachers || []),
        ...(teacherList || [])
      ], 'id')
      transferIds.teacherIds = (teacherList || []).map(x => x.id)
      transferData.teacherIds = uniqBy([
        ...(teachers || []),
        ...(teacherList || [])
      ], 'id')
      // 儿保医生
      transferIds.doctorIds = (doctorList || []).map(x => x.id)
      transferData.doctorIds = uniqBy([
        ...(doctors || []),
        ...(doctorList || [])
      ], 'id')
      // 学生
      transferIds.childrenIds = (childrenList || []).map(x => x.id)
      transferData.childrenIds = uniqBy([
        ...(children || []),
        ...(childrenList || [])
      ], 'id')
      this.transferIds = { ...transferIds }
      this.transferData = { ...transferData }
    },
    async submitHandle () {
      const values = await this.$refs.form.submitForm()
      const { transferIds, id } = this
      const { beginMonth, endMonth } = this.info
      // if (transferIds.inChargeTeacherId.length === 0) {
      //   this.$message.error('请选择班主任')
      //   return
      // }
      transferIds.inChargeTeacherId[0] = values.inChargeTeacherId
      console.log(values, transferIds)
      const params = {
        ...omit(values, ['monthRange', 'teacherIds', 'inChargeTeacherId', 'doctorIds', 'childrenIds']),
        teachingAreaIds: values.teachingAreaIds.join(),
        beginMonth,
        endMonth,
        classId: id || null,
        areaId: this.curArea.areaId
      }
      for (const key in transferIds) {
        params[key] = transferIds[key].join()
      }
      console.log(params)
      this.submitting = true
      submitClass(params).then(res => {
        if (res) {
          this.$message.success('保存成功')
          this.$emit('getList')
          this.$_handleCancel()
        }
      }).finally(() => {
        this.submitting = false
      })
    },
    $_handleCancel () {
      this.visibleDialog = false
    }
  }
}
</script>

<style lang="scss">
  .el-transfer-panel{
    width: 400px;
  }

  .el-transfer__buttons{
    padding: 0px 10px;
  }

  .el-transfer-panel__item{
    height: 30px;
    display: inline-block !important;
    margin-right: 10px;
    min-width: 110px;
  }
</style>
